<template>
  <!-- 活动管理-社区管理页面 -->
  <div class="app-container detail calendar-list-container">
    <!-- 搜索工具栏 -->
    <section>
      <so-tool-bar :toolData="toolData" :query="listQuery" @search="search" />
    </section>
    <!-- 其他操作 -->
    <section class="filter-container">
      <el-row>
        <el-col :span="15">
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(1)">置顶</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(0)">取消置顶</el-button>
        </el-col>
        <el-col :span="9">
          <section style="float: right">
            <el-button class="filter-item" type="danger" size="small" @click="delRows">批量删除</el-button>
            <el-button class="filter-item" type="primary" size="small" @click="openForm('add')">发帖</el-button>
          </section>
        </el-col>
      </el-row>
    </section>
    <!-- 表格 -->
    <el-table :data="tableList" v-loading="loading" element-loading-text="正在查询中。。。" stripe highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" width="30">
        <template slot-scope="scope">
          <i class="iconfont ali-zhiding" v-show="scope.row.top_status == 1"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" label="主题" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="点击查看详情" placement="top">
            <el-button size="mini" type="text" @click="lookArticle(scope.row)">{{scope.row.proposal_title}}</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="作者" prop="create_username">
      </el-table-column>
      <el-table-column align="center" label="发布时间" prop="create_time">
      </el-table-column>
      <el-table-column align="center" label="评论量" prop="comment_nums">
      </el-table-column>
      <el-table-column align="center" label="点赞量" prop="like_nums">
      </el-table-column>
      <el-table-column align="center" label="浏览量" prop="browse_nums">
      </el-table-column>
      <el-table-column align="center" label="评论">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.comment" size="mini" active-color="#13ce66" inactive-color="#C0C4CC" @change="switchChange(scope.row,$event)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-tag size="mini" :type="audit_status[scope.row.audit_status].type">{{audit_status[scope.row.audit_status].name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="列表链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/proposalHome' + '&nameLink=' + 'proposalAdd'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="详情链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/proposalDetail' + '?id=' + scope.row.id + '&name=' + 'proposal'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150px">
        <template slot-scope="scope">
          <el-button v-if="companyId !== 3" type="text" size="mini" :disabled="scope.row.audit_status != 0" @click="pass(1,scope.row)">通过</el-button>
          <el-button v-if="companyId !== 3" type="text" size="mini" :disabled="scope.row.financeaudit_status != 0" @click="openFinance(scope.row)">财务审核</el-button>
          <el-button v-if="companyId !== 3" type="text" size="mini" :disabled="scope.row.audit_status != 0" @click="pass(2,scope.row)">不通过</el-button>
          <el-button type="text" size="mini" @click="openForm('edit',scope.row)">编辑</el-button>
          <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <section>
      <so-pagination :query="listQuery" @initList="initList" />
    </section>
    <!-- 发帖 -->
    <section>
      <el-dialog :visible.sync="dialog.isShow" :show-close="false" width="900px" :fullscreen="fullscreen" :before-close="beforeClose" :close-on-click-modal="false">
        <el-row slot="title">
          <el-col :span="10" style="padding-top: 5px">
            <span style="font-size: 18px;">{{dialog.title}}</span>
          </el-col>
          <el-col :span="2" :offset="11">
            <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
            <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
          </el-col>
          <el-col :span="1">
            <el-button type="text" icon="iconfont ali-guanbi" @click="dialog.isShow = false" style="float: right"></el-button>
          </el-col>
        </el-row>
        <el-form :model="form" ref="createArticle" label-width="90px">
          <el-form-item label="主题" prop="proposal_title" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入主题" v-model.trim="form.proposal_title">
            </el-input>
          </el-form-item>
          <el-form-item label="活动封面" prop="file_path" :rules="filter_rules({type: 'upload'})">
            <img v-if="form.file_path" :src="form.file_path" class="avatar" @click="sizeSet">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
          </el-form-item>
          <el-form-item label="现状描述">
            <UE :defaultMsg.sync='defaultMsg.val1' ref="ue1"></UE>
          </el-form-item>
          <el-form-item label="改进方案">
            <UE @showUpload="showUpload(1)" @showUploadOther="showUpload(2)" config="vuploadother" :defaultMsg.sync='defaultMsg.val2' ref="ue2"></UE>
          </el-form-item>
          <el-form-item label="效益预测" prop="file_path" :rules="filter_rules({type: 'upload'})">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="form.benefit_calculation">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog.isShow = false">取 消</el-button>
          <el-button type="primary" @click="validate('createArticle')">提 交</el-button>
        </span>
      </el-dialog>
    </section>
    <section>
      <size-temp ref="size" :img.sync="form.file_path" title="图片设置"></size-temp>
    </section>
    <section>
      <finance ref="finance" @initList="initList"></finance>
    </section>
    <section>
      <UeUpload ref="vupload1" @addUeditorImg="addUeditorImg(1,$event)" img="卐" title="添加图片"></UeUpload>
    </section>
    <section>
      <UeUpload ref="vupload2" @addUeditorImg="addUeditorImg(2,$event)" img="卐" title="添加图片"></UeUpload>
    </section>
  </div>
</template>
<script>
import { searchTool } from '@/utils'
import { advice_list,advice_updateTopStatus,advice_delete,advice_deleteAll,advice_edit,advice_save } from '@/api/advice'
import UE from '@/components/Ueditor';
import SoPagination from '@/components/SoPagination'
import SoToolBar from '@/components/SoToolBar'
import { status_opt, audit_status, toolData } from './advice'
import sizeTemp from '@/components/draggableSize'
import UeUpload from '@/components/UeUpload'

import finance from './finance'

export default {
  name: "communityManage",
  components:{ SoPagination, SoToolBar, sizeTemp, finance, UE, UeUpload },
  data() {
    return {
      toolData: toolData, //搜索工具栏初始化
      loading: false,
      tableList: [],
      multipleSelection: [],
      listQuery: { start: 0, limit: 10, total: 0, current: 1,  moule_id: 1 },
      audit_status: audit_status,
      status_opt: status_opt,
      dialog: {isShow: false,},
      fullscreen: false ,
      fromStatus:'',
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      companyId: localStorage.getItem("companyId") -0,
      form: {file_path: ''},
      defaultMsg: {val1: '', val2: ''}
    }
  },
  methods: {
    onCopy: function() {
      this.$message({
        type: "success",
        message: "复制成功"
      });
    },
    onError: function() {
      this.$message.error("复制失败");
    },
    showUpload(num){
      this.$refs[`vupload${num}`].open()
    },
    addUeditorImg(num, val){
      this.$refs[`ue${num}`].addToContent(`<img src="${val}">`)
    },
    beforeClose(done){
      this.$refs.ue1.clear();
      this.$refs.ue2.clear();
      done()
    },
    openFinance(row){
      this.$refs.finance.show(row);
    },
    sizeSet(){
      this.$refs.size.open()
    },
    async delRow(data) {
      let Id = data.id  //删除
      try {
        let res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          let { data } = await advice_delete({ id: Id });
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
          this.loading = false;
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    lookArticle(e){
      this.$router.push({path: '/activity/adviceDetail',query: {id: e.id}})
    },
    async pass(num, e){//待审核为0,通过为1,不通过为2
      e.audit_status = num;
      this.loading = true;
      await advice_edit(e)
      this.loading = false;
      this.initList();
    },
    openForm(e,row){//打开发帖dialog
      if(e == 'add'){
        this.fromStatus = 'add'
        this.form = {file_path: ''}
        this.dialog = { isShow: true, title: '发帖'}
        this.defaultMsg = {val1: '', val2: ''};
        this.$nextTick(_ => {
          this.$refs.ue1.setContent('<br/>'); //清空富文本
          this.$refs.ue2.setContent('<br/>'); //清空富文本
        });
      }else{
        this.fromStatus = 'edit';
        this.dialog = { isShow:true, title:'编辑'}
        this.form  = row;
        this.defaultMsg = {
          val1: row.actuality_description,
          val2: row.improvement_scheme
        }
        this.$nextTick((_=>{
          this.$refs.ue1.setContent(this.defaultMsg.val1)
          this.$refs.ue2.setContent(this.defaultMsg.val2)
        }))
      }

    },
     async saveObj(){
      const params = {...this.form, moule_id: 1, company_id: localStorage.getItem("companyId") - 0};
      this.loading = true;
      let { data } = this.fromStatus =='add' ? await advice_save(params) : await advice_edit(params);
      this.loading = false;
      if(data.status == 100){
        this.$message.success(this.fromStatus ? '提交成功':'编辑成功')
        this.initList();
      }
    },
    validate(e){
      this.form.actuality_description = this.$refs.ue1.getContent();//富文本内容
      this.form.improvement_scheme = this.$refs.ue2.getContent();//富文本2内容
      this.$refs[e].validate((valid) => {
        if (valid) {
          this.saveObj();
          this.dialog.isShow = false
        }else{
          return false;
        }
      });
    },
    beforeAvatarUpload(file) {
      let name = file.name.split(".");
      if (
        name[name.length - 1] === "jpg" ||
        name[name.length - 1] === "jpeg" ||
        name[name.length - 1] === "png"
      ) {
        return file;
      } else {
        this.$message.error("图片只能是 jpeg/png 格式!");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.file_path = this.ossPublicUrl + "/" + res.data.file_path;
    },

    async delRows(){//批量删除
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      try {
        const res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          const { data } = await advice_deleteAll({array: ids});
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    async haveTop(e){//1 置顶 0 取消
      if(this.multipleSelection.length == 0){
        this.$message.warning('请先选择需要调整单元');
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      this.loading = true;
      let { data } = await advice_updateTopStatus({ids: ids, top_status: e});
      this.loading = false;
      if(data.status === 100){
        await this.initList();
        this.$message.success('操作成功');
      }
    },
    async switchChange(row,e){//是否可评论
      const params = {...row, comment_status: ~~e}//取消内存引用问题
      this.loading = true;
      await advice_edit(params)
      this.loading = false;
      this.initList();
    },
    search() {//搜索
      let keyWords = {key: 'searchDate', names: ['create_starttime', 'create_endtime']}
      this.listQuery = searchTool(this.listQuery, keyWords);
      this.initList();
    },
    async initList(){
      this.loading = true
      const query = {...this.listQuery,company_id: localStorage.getItem('companyId') - 0};
      let { data } = await advice_list(query);
      this.loading = false
      if(data.status == 100){
        this.tableList = data.data.rows.map( item => {
          return {...item, comment: !!item.comment_status}
        })
        this.listQuery.total = data.data.results;
      }
    },
    handleSelectionChange(e){//
       this.multipleSelection = e;
    },
  },
  created(){
    this.initList();
  }
}
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
span {
  font-size: 13px;
  color: $color;
}
.ali-zhiding {
  color: #009900;
  font-size: 20px;
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
</style>
